<template>
    <div class="home_div">
        <!-- <div class="map-title">
            <h3>JSAPI Vue3地图组件示例</h3>
            <div v-if="back" id="back" @click="showAllMap" style="cursor: pointer;">返回</div>
        </div> -->
        <div id="container"></div>
        <div class="floating-panel">
            <div v-for="(item, index) in floatingItems" :key="index" class="floating-item">
                <img :src="item.icon" :alt="item.name" class="item-icon" />
                <span class="item-name">{{ item.name }}</span>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>

import AMapLoader from "@amap/amap-jsapi-loader";
import { shallowRef } from "@vue/reactivity";
import { ref, onMounted, reactive } from "vue";
import { qingyunMapData } from '@/utils/qingyuntest'
    const map = shallowRef(null) as any;
    const AMap = shallowRef<any>(null) as any;
    const back = ref(false);
    const polygons = shallowRef([]) as any; // 区描边、遮罩
    const district = shallowRef(null) as any;
    const polygon = shallowRef(null) as any; // 市描边、遮罩
    const markers = shallowRef([]) as any; // 自定义标记点、
    const floatingItems = ref([
        {
            icon: 'https://image.shengxuankj.com/daping/blue.png',
            name: '换电柜'
        }
    ]);
    // 类型定义
    interface MarkerDataTs {
        longitude: number
        latitude: number
        name: string
        icon: string
        [key: string]: any

    }
    const markerData = ref<MarkerDataTs[]>([])
    const getDataList = () => {
        let list: any = [[]]
        qingyunMapData.features[0].geometry.coordinates[0].forEach((item: any) => {
            // console.log(item);
            list[0].push(new AMap.value.LngLat(item[0], item[1]))
        })
        return list
    }
        // 初始化遮罩
    const initArea = (city: string, isChildDraw: boolean = false) => {
        district.value.search(city, function (status: string, result: any) {
            // 外多边形坐标数组和内多边形坐标数组
            const outer = [
                new AMap.value.LngLat(-360, 90, true),
                new AMap.value.LngLat(-360, -90, true),
                new AMap.value.LngLat(360, -90, true),
                new AMap.value.LngLat(360, 90, true),
            ];
            // console.log(result);

            // 绘制遮罩
            var holes = getDataList();
            console.log(holes);

            var pathArray = [outer];
            pathArray.push.apply(pathArray, holes);
            polygon.value = new AMap.value.Polygon({
                pathL: pathArray,
                strokeColor: "#253042",
                strokeWeight: 1,
                fillColor: "#071023",
                fillOpacity: 1,
            });
            polygon.value.setPath(pathArray);
            map.value.add(polygon.value);

            // 点击事件
            polygon.value.on('click', (e: any) => {
                console.log(e);
            })
            // areaPolyline(result.districtList[0].districtList[0].adcode)
            // 判断是否要绘制子区域
            // if (isChildDraw) {
            //     // 将搜索层级设置为 区、县
            //     that.district.setLevel("district");
            //     for (let i = 0; i < result.districtList[0].districtList.length; i++) {
            //         that.areaPolyline(result.districtList[0].districtList[i].adcode);
            //     }
            // }
        });
    }
    // const initArea = (city: string, isChildDraw: boolean = false): void => {
    //     district.value.search(city, function (status: string, result: any) {
    //         // 外多边形坐标数组和内多边形坐标数组
    //         const outer = [
    //             new AMap.value.LngLat(-360, 90, true),
    //             new AMap.value.LngLat(-360, -90, true),
    //             new AMap.value.LngLat(360, -90, true),
    //             new AMap.value.LngLat(360, 90, true),
    //         ];
    //         console.log(result);

    //         // 绘制遮罩
    //         const holes = result.districtList[0].boundaries;
    //         const pathArray = [outer];
    //         pathArray.push.apply(pathArray, holes);
    //         polygon.value = new AMap.value.Polygon({
    //             pathL: holes,
    //             strokeColor: "#253042",
    //             strokeWeight: 1,
    //             fillColor: "#071023",
    //             fillOpacity: 1,
    //         });
    //         polygon.value.setPath(pathArray);
    //         map.value.add(polygon.value);
    //         areaPolyline(result.districtList[0].districtList[0].adcode)
    //     });
    // };
    // 添加自定义标记点
    const addCustomMarkers = () => {
        // 清除已有标记点
        if (markers.value.length) {
            map.value.value.remove(markers.value);
            markers.value = [];
        }
        
        // 定义四个点位的坐标和信息
        // const markerData = [
        //     {
        //         position: [117.400507, 37.847724], // 点位1坐标
        //         title: '点位1',
        //         content: '这是第一个标记点'
        //     },
        //     {
        //         position: [117.440507, 37.807724], // 点位2坐标
        //         title: '点位2',
        //         content: '这是第二个标记点'
        //     },
        //     {
        //         position: [117.380507, 37.817724], // 点位3坐标
        //         title: '点位3',
        //         content: '这是第三个标记点'
        //     },
        //     {
        //         position: [117.460507, 37.837724], // 点位4坐标
        //         title: '点位4',
        //         content: '这是第四个标记点'
        //     }
        // ];
        
        // 创建自定义图标
        // const customIcon = new this.AMap.Icon({
        //     size: new this.AMap.Size(32, 32), // 图标大小
        //     image: 'data:image/svg+xml;base64,' + btoa(`
        //         <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
        //             <circle cx="16" cy="16" r="12" fill="#FF6600" stroke="#fff" stroke-width="2"/>
        //             <circle cx="16" cy="16" r="6" fill="#fff"/>
        //         </svg>
        //     `), // 自定义SVG图标
        //     imageSize: new this.AMap.Size(32, 32)
        // });
        
        // 创建标记点
        console.log('标点啦~~~~',markerData.value)
        markerData.value.forEach((data, index) => {
            // 创建自定义图标
            const customIcon = new AMap.value.Icon({
                size: new AMap.value.Size(20, 20), // 图标大小
                image: data.icon, // 引用服务器SVG图标
                imageSize: new AMap.value.Size(20, 20)
            });
            const marker = new AMap.value.Marker({
                position: [data.longitude, data.latitude],
                icon: customIcon,
                title: data.name,
                offset: new AMap.value.Pixel(-16, -16), // 图标偏移量
            });
            
            // 添加点击事件
            marker.on('click', () => {
                const infoWindow = new AMap.value.InfoWindow({
                    content: `<div style="padding: 10px;"><h4>${data.name}</h4></div>`,
                    offset: new AMap.value.Pixel(0, -30)
                });
                infoWindow.open(map.value, [data.longitude, data.latitude]);
            });
            
            markers.value.push(marker);
        });


        // 创建标记点
        // markerData.forEach((data, index) => {
        //     const marker = new this.AMap.Marker({
        //         position: data.position,
        //         icon: customIcon,
        //         title: data.title,
        //         offset: new this.AMap.Pixel(-16, -16) // 图标偏移量
        //     });
            
        //     // 添加点击事件
        //     marker.on('click', () => {
        //         const infoWindow = new this.AMap.InfoWindow({
        //             content: `<div style="padding: 10px;"><h4>${data.title}</h4><p>${data.content}</p></div>`,
        //             offset: new this.AMap.Pixel(0, -30)
        //         });
        //         infoWindow.open(this.map, data.position);
        //     });
            
        //     this.markers.push(marker);
        // });
        // ===================
        
        // 添加到地图
        map.value.add(markers.value);

    }
    // 显示总览
    const showAllMap = () => {
        back.value = false;
        if (polygon.value) {
            // 清除遮罩
            map.value.remove(polygon.value);
        }
        // this.initArea("渤海路街道", true);
        // this.map.setCenter([118.113994, 24.614998]);
        map.value.setCenter([117.383037, 37.786794]);
        map.value.setZoom(11);
        // 重新添加标记点
        addCustomMarkers();
    }
        // 绘制区域描边
    // const areaPolyline = (adcode: string) => {
    //         let that = this;
    //         if (polygons.value.length) {
    //             map.value.remove(polygons.value);
    //             polygons.value = [];
    //         }
    //         district.value.search(adcode, function (status: string, result: any) {
    //             console.log("区", result);
    //             //   绘制区域描边
    //             let bounds = result.districtList[0].boundaries;
    //             for (let i = 0; i < bounds.length; i++) {
    //                 const color = that.getColorByAdcode(result.districtList[0].adcode);
    //                 const polygon = new that.AMap.Polygon({
    //                     path: bounds[i],
    //                     strokeColor: "#253042",
    //                     strokeWeight: 2,
    //                     fillColor: "#784eda",
    //                     fillOpacity: 0,
    //                 });
    //                 // 添加监听事件
    //                 // polygon.on("mouseover", () => {
    //                 //     if (!that.back) {
    //                 //         polygon.setOptions({
    //                 //             fillOpacity: 0.7,
    //                 //         });
    //                 //     }
    //                 // });
    //                 // 添加点击事件
    //                 polygon.on("click", () => {
    //                     console.log('点击了', result.districtList[0].adcode);


    //                     // 判断是否为市级
    //                     // if (!that.back) {
    //                         // 显示返回按钮
    //                         that.map.setZoom(12);
    //                         // 修改中心位置为区级中心
    //                         that.map.setCenter([
    //                             result.districtList[0].center.lng,
    //                             result.districtList[0].center.lat,
    //                         ]);
    //                         //   绘画
    //                         that.initArea(result.districtList[0].adcode, false);
    //                     // }
    //                 });
    //                 polygon.on("mouseout", () => {
    //                     polygon.setOptions({
    //                         fillOpacity: 0,
    //                     });
    //                 });
    //                 that.polygons.push(polygon);
    //             }
    //             that.map.add(that.polygons);
    //         });
    //     },
    const areaPolyline = (adcode: string): void => {
        if (polygons.value.length) {
            map.value.remove(polygons.value);
            polygons.value = [];
        }
        district.value.search(adcode, function (status: string, result: any) {
            //   绘制区域描边
            const bounds = result.districtList[0].boundaries;
            for (let i = 0; i < bounds.length; i++) {
                // const color = getColorByAdcode(result.districtList[0].adcode);
                const polygonItem = new AMap.value.Polygon({
                    path: bounds[i],
                    strokeColor: "#253042",
                    strokeWeight: 2,
                    fillColor: "#784eda",
                    fillOpacity: 0,
                });
                // 添加点击事件
                polygonItem.on("click", () => {
                    // 判断是否为市级
                    if (!back.value) {
                        // 显示返回按钮
                        back.value = true;
                        map.value.setZoom(12);
                        // 修改中心位置为区级中心
                        map.value.setCenter([
                            result.districtList[0].center.lng,
                            result.districtList[0].center.lat,
                        ]);
                        //   绘画
                        // initArea(result.districtList[0].adcode, false);
                    }
                });
                polygonItem.on("mouseout", () => {
                    polygonItem.setOptions({
                        fillOpacity: 0,
                    });
                });
                polygons.value.push(polygonItem);
            }
            map.value.add(polygons.value);
        });
    }
    const getMaskJson = (): any => {
        const list = qingyunMapData.features[0].geometry.coordinates[0];
        return list;
    };
    const ininMap = async () => {

        // 这个配置很重要，必须设置，否则你的 行政服务搜索api无法使用生成回调
        (window as any)._AMapSecurityConfig = {
            securityJsCode: "587b22815e6cc6b14effaa607c627fb7",
        };
        AMapLoader.load({
            key: "e6072f86d2d66d78671eaa4542006354", //设置您的key
            version: "2.0",
            plugins: [
                "AMap.ToolBar",
                "AMap.Driving",
                "AMap.Polygon",
                "AMap.DistrictSearch",
                "AMap.Object3DLayer",
                "AMap.Object3D",
                "AMap.Polyline",
                "AMap.Marker",
                "AMap.InfoWindow",
                "AMap.Icon"
            ],
            AMapUI: {
                version: "1.1",
                plugins: [],
            },
            Loca: {
                version: "2.0.0",
            },
        }).then((AMapInstance) => {
            AMap.value = AMapInstance;
            map.value = new AMapInstance.Map("container", {
                viewMode: "3D",
                zoom: 12.5,
                zooms: [10, 13],
                center: [117.383037, 37.786794],
                mapStyle: "amap://styles/dark",
                features: ["bg", "road"],
                // mask: getMaskJson()
            });
            district.value = new AMapInstance.DistrictSearch({
                subdistrict: 3, //获取边界返回下级行政区
                extensions: "all", //返回行政区边界坐标组等具体信息
                // level: "city", //查询行政级别为 市
                level: "district", //查询行政级别为 市

            });
            console.log('district===============================',district.value)

            initArea("渤海路街道", true);
            // 添加自定义标记点
            addCustomMarkers();

            // 点击事件
            map.value.on('click', (e: any) => {
                console.log(e);
            })


        })
        .catch((e) => {
            console.log(e);
        });
    }
    onMounted(()=> {
        let timer = setTimeout(() => {
            ininMap();
            clearTimeout(timer);
        }, 500);
    })
    const getPointData = (pointList: any) => {
        console.log('获取点位啦~~~~',pointList)
        markerData.value = JSON.parse(pointList).mapPoints
    }


    defineExpose({
        getPointData
    })
</script>
<style scope>
.home_div {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
    position: relative;
}

#container {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
}

.map-title {
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 50px;
    background-color: rgba(27, 25, 27, 0.884);
    display: flex;
    justify-content: space-around;
    align-items: center;
}

h3 {
    z-index: 2;
    color: white;
}

/* 悬浮框样式 */
.floating-panel {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.8);
    border-radius: 8px;
    padding: 15px 20px;
    /* min-width: 200px; */
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.floating-item {
    display: flex;
    align-items: center;
    /* margin-bottom: 12px; */
    padding: 8px;
    border-radius: 6px;
    transition: background-color 0.3s ease;
}

.floating-item:last-child {
    margin-bottom: 0;
}

/* .floating-item:hover {
    background-color: rgba(255, 255, 255, 0.1);
    cursor: pointer;
} */

.item-icon {
    width: 24px;
    height: 24px;
    margin-right: 12px;
    border-radius: 4px;
    object-fit: cover;
}

.item-name {
    color: #ffffff;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
}
</style>